<template>
    <div class="hello">
        <ul>
            <transition-group class="transition-wrapper" name="sort">
                <li
                    v-for="(item, index) in addList"
                    :key="item.id"
                    :draggable="true"
                    @dragstart="dragstart(item)"
                    @dragenter="dragenter(item, $event)"
                    @dragend="dragend(item, $event)"
                    @dragover="dragover($event)"
                >
                    {{ item.name }}
                    <button @click="goUporDown(1, index)">上移</button>
                    <button type="danger" @click="goUporDown(2, index)">下移</button>
                </li>
            </transition-group>
        </ul>
    </div>
</template>

<script>
export default {
    name: 'drap',
    data() {
        return {
            addList: [
                {
                    id: 1,
                    name: '1'
                },
                {
                    id: 2,
                    name: '2'
                },
                {
                    id: 3,
                    name: '3'
                },
                {
                    id: 4,
                    name: '4'
                }
            ],
            oldValue: null,
            newValue: null
        }
    },
    methods: {
        // 当移动移入某个元素时触发
        dragover(e) {
            // 禁止默认事件触发
            e.preventDefault()
        },
        // 鼠标拖动当前元素时触发
        dragstart(v) {
            this.oldValue = v
        },
        // 鼠标松开进入某个容器时触发
        dragenter(v, e) {
            this.newValue = v
        },
        // 鼠标完成拖动后触发
        dragend(v, e) {
            // eslint-disable-next-line no-useless-return
            if (this.newValue === this.oldValue) return
            // 拿到旧节点index
            let oldIndex = this.addList.indexOf(this.oldValue)
            // 拿到新节点index
            let newIndex = this.addList.indexOf(this.newValue)
            this.addList.splice(oldIndex, 1) // 先删
            this.addList.splice(newIndex, 0, this.oldValue) // 再增
        },
        goUporDown(type, index) {
            if (type === 1 && index > 0) {
                let lsitDel = this.addList.splice(index, 1) // 先删除
                this.addList.splice(index - 1, 0, lsitDel[0]) // 再增
            } else if (type === 2 && index < this.addList.length - 1) {
                let listAdd = this.addList.splice(index, 1)
                this.addList.splice(index + 1, 0, listAdd[0])
            }
        }
    }
}
</script>

<style scoped>
ul {
    list-style-type: none;
    padding: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
}
li {
    margin-bottom: 10px;
    width: 200px;
    height: 50px;
    background: #42b983;
}
a {
    color: #42b983;
}
</style>
